<template>
  <div class="">
    <h1 class="text-base font-semibold leading-7 text-gray-900">
      {{ $t('pageAlarmSetting.description') }}
    </h1>
    <div class="text-right">
      <div class="mb-2 items-center text-sm">
        {{ $t('pageAlarmSetting.remoteServer.remoteTitleLabel') }}
      </div>
      <el-text
        v-if="!remoteAddress"
        class="mx-1 cursor-pointer"
        type="primary"
        @click="openDialog"
      >
        {{ $t('pageAlarmSetting.remoteServer.addServer') }}
      </el-text>
      <div v-else>
        <p class="inline">{{ remoteAddress }}</p>
        <el-button-group class="ml-4">
          <el-button @click="openDialog" :icon="Edit" />
          <el-popconfirm
            title="Are you sure to delete this?"
            @confirm="deleteServer"
          >
            <template #reference>
              <el-button :icon="Delete" />
            </template>
          </el-popconfirm>
        </el-button-group>
      </div>
    </div>

    <div class="mb-2 flex items-center text-sm">
      {{ $t('pageAlarmSetting.Managers') }}
    </div>
    <el-form :model="tableData" ref="formRef">
      <el-table
        :data="tableData.snmpManagers"
        class="mb-0"
        :empty-text="$t('global.table.emptyMessage')"
      >
        <el-table-column
          prop="address"
          :label="$t('pageAlarmSetting.table.address')"
          align="center"
        >
          <template #default="scope">
            <el-form-item
              :prop="'snmpManagers.' + scope.$index + '.address'"
              :rules="[
                {
                  required: true,
                  message: $t('global.form.fieldRequired'),
                  trigger: 'change',
                },
              ]"
            >
              <el-input
                v-model="scope.row.address"
                type="text"
                style="width: 100%"
                placeholder=""
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          prop="port"
          :label="$t('pageAlarmSetting.table.port')"
          align="center"
        >
          <template #default="scope">
            <el-form-item
              :prop="'snmpManagers.' + scope.$index + '.port'"
              :rules="[
                {
                  required: true,
                  message: $t('global.form.fieldRequired'),
                  trigger: 'change',
                },
                {
                  type: 'number',
                  min: 1,
                  max: 65535,
                  message: $t('global.form.invalidFormat'),
                  trigger: 'change',
                },
              ]"
            >
              <el-input v-model.number="scope.row.port"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200">
          <template #default="scope">
            <el-button
              size="small"
              type="danger"
              class="bg-orange-600"
              @click="handleDelete(scope.$index)"
              >{{ $t('global.action.delete') }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <el-text
      class="mx-1 cursor-pointer"
      type="primary"
      @click="handleAddManage"
    >
      {{ $t('pageAlarmSetting.table.addmanager') }}
    </el-text>

    <div class="text-right">
      <el-button @click="cancel"> {{ $t('global.action.cancel') }}</el-button>
      <el-button type="primary" @click="submitForm">
        {{ $t('global.action.saveSettings') }}</el-button
      >
    </div>
  </div>
  <alarm-setting-dialog
    ref="AlarmSettingDialogRef"
    :remote-address="remoteAddress"
    :remote-port="remotePort"
  />
</template>

<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import AlarmSettingDialog from './AlarmSettingDialog.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useAlarmSettingStore } from '@/store/ServicesManagement/AlarmSetting/AlarmSettingStore';
import { Delete, Edit } from '@element-plus/icons-vue';

const alarmSettingStore = useAlarmSettingStore();
const i18n = useI18n();
const AlarmSettingDialogRef = ref();

interface SnmpManager {
  address: string;
  port: number;
  path?: string;
  updateAddress?: string;
  updatePort?: number;
}

await alarmSettingStore.getRemoteServer();

const remoteAddress = computed(() => {
  return alarmSettingStore.remoteServer.Address;
});
const remotePort = computed(() => {
  return alarmSettingStore.remoteServer.Port;
});

const managersToDelete = ref([] as any[]);

const tableData = reactive({
  snmpManagers: [] as SnmpManager[],
});

const formErrors = reactive<any[]>([]);

const validateForm = async () => {
  formErrors.length = tableData.snmpManagers.length;
  for (let i = 0; i < tableData.snmpManagers.length; i++) {
    formErrors[i] = {};
    if (!tableData.snmpManagers[i].address) {
      formErrors[i].address = i18n.t(
        'pageAlarmSetting.remoteServer.modal.invalidfeedback1',
      );
    }
    if (
      tableData.snmpManagers[i].port == null ||
      tableData.snmpManagers[i].port! < 1 ||
      tableData.snmpManagers[i].port! > 65535
    ) {
      formErrors[i].port = i18n.t(
        'pageAlarmSetting.remoteServer.modal.formText2',
      );
    }
  }
  return formErrors.every((error) => !Object.keys(error).length);
};

const updateManagersSettings = async () => {
  // Validate that no field are empty and port is valid. Port value is
  // undefined if it is an invalid number.
  for (let i in tableData.snmpManagers) {
    if (!tableData.snmpManagers[i].address || !tableData.snmpManagers[i].port) {
      ElMessage({
        type: 'error',
        message: i18n.t('pageAlarmSetting.toast.errorSave'),
      });
      return;
    }
  }
  let managersLength = tableData.snmpManagers.length;
  let errorTag = false;
  while (managersLength--) {
    // If the manager does not have a 'path', it is a new manager
    // and needs to be created
    if (!tableData.snmpManagers[managersLength].path) {
      await alarmSettingStore
        .addManager({
          address: tableData.snmpManagers[managersLength].address,
          port: tableData.snmpManagers[managersLength].port,
        })
        .catch(() => {
          errorTag = true;
          ElMessage({
            type: 'error',
            message: i18n.t('pageAlarmSetting.toast.errorSave'),
          });
        });
    } else {
      if (tableData.snmpManagers[managersLength].updateAddress) {
        await alarmSettingStore
          .setManagerAddress({
            path: tableData.snmpManagers[managersLength].path as string,
            address: tableData.snmpManagers[managersLength].address,
          })
          .catch(() => {
            errorTag = true;
            ElMessage({
              type: 'error',
              message: i18n.t('pageAlarmSetting.toast.errorSave'),
            });
          });
      }
      if (tableData.snmpManagers[managersLength].updatePort) {
        await alarmSettingStore
          .setManagerPort({
            path: tableData.snmpManagers[managersLength].path as string,
            port: tableData.snmpManagers[managersLength].port,
          })
          .catch(() => {
            errorTag = true;
            ElMessage({
              type: 'error',
              message: i18n.t('pageAlarmSetting.toast.errorSave'),
            });
          });
      }
    }
  }
  // delete all items in managersToDelete
  for (let i in managersToDelete.value) {
    await alarmSettingStore
      .deleteManager(managersToDelete.value[i])
      .catch(() => {
        errorTag = true;
        ElMessage({
          type: 'error',
          message: i18n.t('pageAlarmSetting.toast.errorSave'),
        });
      });
  }
  if (!errorTag) {
    ElMessage({
      type: 'success',
      message: i18n.t('pageAlarmSetting.toast.successSave'),
    });
    getList();
  }
};

const openMessage = () => {
  ElMessageBox.confirm(
    i18n.t('pageAlarmSetting.modal.confirmMessage'),
    i18n.t('pageAlarmSetting.modal.confirmTitle'),
    {
      confirmButtonText: i18n.t('global.action.saveSettings'),
      cancelButtonText: i18n.t('global.action.cancel'),
    },
  )
    .then(() => {
      updateManagersSettings();
    })
    .catch(() => {
      cancel();
    });
};

const handleAddManage = () => {
  alarmSettingStore.addNewSNMPManager();
};

const openDialog = () => {
  AlarmSettingDialogRef.value.open = true;
};

const handleDelete = (index: number) => {
  alarmSettingStore.deleteManagerTableRow(index);
};

const submitForm = async () => {
  if (!tableData.snmpManagers.length) return;
  if (await validateForm()) {
    openMessage();
  } else {
    ElMessage.error(i18n.t('pageAlarmSetting.toast.validationFailed'));
  }
};

const cancel = () => {
  getList();
};

const getList = () => {
  alarmSettingStore.getManagerData().finally(() => {
    tableData.snmpManagers = alarmSettingStore.snmpManagers;
    managersToDelete.value = alarmSettingStore.managersToDelete;
  });
};

getList();

const deleteServer = async () => {
  await alarmSettingStore.deleteServer();
  await alarmSettingStore.getRemoteServer();
  AlarmSettingDialogRef.value.reset();
};
</script>
